/* api */
import * as RepositoryApi from '@src/api/Repository'
/* vue */
import { defineComponent, CreateElement } from "vue"
/* util */
import { isFalsy } from "@src/util/type"
import { asyncErrorCaptured } from "@src/util/onerror"
import platform from "@src/platform"
import { t } from "@src/locales"
import { getRootWindow } from "pub-bbx-utils"

enum WikiNodeKeyEnum {
  DRAFT = 'draft',
  PUBLISHED = 'wiki',
  COLLECTION = 'collection',
  RECORD = 'record',
  UNPUBLISHED = 'unpublished',
  FAULTLIBRARY = 'faultLibrary'
}

type TreeItem = { id: string, name: string, type: number, count?: number, subTypes?: TreeItem[] }
type TreeData = TreeItem[]

export default defineComponent({
  name: "WikiTreeDialogTree",
  props: {
    value: {
      type: Array as () => string[],
      default: () => []
    }
  },
  data() {
    return {
      expandedTreeList: [] as string[],
      nodeLabelEllipsis: true,
      treeData: [] as TreeData,
      defaultCheckedKeys: [] as string[],
      loading: false
    }
  },
  computed: {
    treeProps() {
      return {
        label: 'name',
        children: 'subTypes'
      }
    },
    // 故障库灰度
    isFaultGrayscale(): boolean {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow?.grayAuth?.faultLibrary)
    },
  },
  watch: {
    value: {
      handler(value: string[]) {
        this.defaultCheckedKeys = value
      },
      immediate: true
    }
  },
  mounted() {
    this.initialize()
  },
  methods: {
    getCheckedKeys() {
      const treeComponent = this.$refs.tree as Record<string, any>
      return treeComponent?.getCheckedKeys() || []
    },
    /**
     * @description 初始化
    */
    async initialize() {
      try {
        
        this.loading = true
        
        await this.fetchWikiTypes()
        await this.fetchFaultTypes()
        await this.fetchCount()
        
        // 设置默认展开的节点
        this.setDefaultExpandedKeys()
        
      } catch (error) {
        console.error('initialize error:', error)
      } finally {
        this.loading = false
      }
    },
    /**
     * @description 获取知识空间分类二级树状结构
     */
    async fetchWikiTypes() {
      
      let [error, result] = await asyncErrorCaptured(RepositoryApi.getDocumentTypes)
      
      if (error) {
        console.error('fetchWikiTypes error:', error)
        return
      }
      
      const isSuccess = Boolean(result?.success)
      const message = result?.message || '获取知识空间分类失败'
      if (isFalsy(isSuccess)) {
        platform.notificationError({ 
          title: message 
        })
        return
      }
      
      const data = result?.result || []
      this.treeData.push({
        id: WikiNodeKeyEnum.PUBLISHED,
        name: t('wiki.list.treeData.label3'),
        subTypes: data,
        type: 0
      })
      
    },
    async fetchFaultTypes() {
      
      if (isFalsy(this.isFaultGrayscale)) {
        console.log('故障库灰度未开启')
        return
      }
      
      const [error, result] = await asyncErrorCaptured(RepositoryApi.getDocumentTypes, [{
        type: 1
      }])
      
      if (error) {
        console.error('fetchFaultTypes error:', error)
        return
      }
      
      const isSuccess = Boolean(result?.success)
      if (isFalsy(isSuccess)) {
        return
      }
      
      const data = result?.result || []
      this.treeData.push({
        id: WikiNodeKeyEnum.FAULTLIBRARY,
        name: t('wiki.list.treeData.label4'),
        subTypes: data,
        type: 1
      })
      
    },
    /**
     * @description 获取知识空间分类数量
     */
    async fetchCount() {
      
      let [error, result] = await asyncErrorCaptured(RepositoryApi.getDocumentViewCount)
      
      if (error) {
        console.error('fetchCount error:', error)
        return
      }
      
      const isSuccess = Boolean(result?.success)
      if (isFalsy(isSuccess)) {
        return
      }
      
      const data = result?.result || {} as Record<string, number>
      
      this.treeData.forEach(item => {
        
        if (item.id == WikiNodeKeyEnum.PUBLISHED) {
          this.$set(item, 'count', data.published || 0)
        }
        
        if (item.id == WikiNodeKeyEnum.FAULTLIBRARY) {
          this.$set(item, 'count', data.faultLibrary || 0)
        }
        
      })
      
    },
    setDefaultExpandedKeys() {
      this.expandedTreeList = this.treeData.map(item => item.id)
    },
    onCurrentChangeHandler() {
    },
    onShowNodeLabelTipsHandler(event: Event) {
      const target = event.target as HTMLElement
      this.nodeLabelEllipsis = target.offsetWidth > 500
    },
    renderNodeIcon(node: { key: string }) {
      
      const { key } = node
      
      if (key === WikiNodeKeyEnum.DRAFT) {
        return <i class="iconfont icon-caogaoxiang" />
      }
      if (key === WikiNodeKeyEnum.PUBLISHED) {
        return <i class="iconfont icon-yifabu" />
      }
      if (key === WikiNodeKeyEnum.COLLECTION) {
        return <i class="iconfont icon-shoucang" />
      }
      if (key === WikiNodeKeyEnum.RECORD) {
        return <i class="iconfont icon-zuijinfangwen" />
      }
      if (key === WikiNodeKeyEnum.UNPUBLISHED) {
        return <i class="iconfont icon-weifabu" />
      }
      
      return <i class="iconfont icon-fenlei1" />
      
    },
    renderNodeLabel(node: { key: string, label: string }, data: { count: number }) {
      
      const count = (data.count || data.count === 0) ? `（${data.count}）` : ''
      const content = `${node.label}${count}`
      const isDisabled = isFalsy(this.nodeLabelEllipsis)
      
      return (
        <el-tooltip 
          class="item" 
          effect="dark" 
          placement="top-start" 
          disabled={isDisabled}
          content={content} 
        >
          <span 
            class="wiki-tree-node-label" 
            onMouseover={this.onShowNodeLabelTipsHandler}
          >
            { content }
          </span>
        </el-tooltip>
      )
      
    },
    renderTreeContent({ node, data }: Record<string, any>) {
      return (
        <span class="wiki-tree-node">
          <span class="wiki-tree-node-block">
            { this.renderNodeIcon(node) }
            { this.renderNodeLabel(node, data) }
          </span>
        </span>
      )
    }
  },
  render(h: CreateElement) {
    
    const attrs = {
      props: {
        props: this.treeProps,
      },
      directives: [
        {
          name: 'loading',
          value: this.loading
        }
      ]
    }
  
    return (
      <el-tree
        {...attrs}
        ref="tree"
        nodeKey="id"
        show-checkbox
        highlightCurrent
        checkOnClickNode
        data={this.treeData}
        defaultExpandedKeys={this.expandedTreeList}
        defaultCheckedKeys={this.defaultCheckedKeys}
        onCurrentChange={this.onCurrentChangeHandler}
        expandOnClickNode={false}
        scopedSlots={{
          default: this.renderTreeContent
        }}
      >
      </el-tree>
    )
  }
})
